import styles from './index.less';
import {
  Card,
  Image,
  Flex,
  Rate,
  Tag,
  Button,
  Selector,
  StickyPosition,
  Dialog,
  Grid,
  GridItem,
  Toast,
} from 'react-vant';
import { useEffect, useState } from 'react';
import {
  Fire,
  FireO,
  Arrow,
  ArrowLeft,
  Replay,
  ShopO,
} from '@react-vant/icons';
import Progress from '@/components/Progress';
import { history, connect } from 'umi';
import { GoodItem, sprite } from '@/utils/myinterface';
export default connect(({ index }) => index)((props) => {
  interface SkillItem {
    name: string;
    type: string;
    power: number;
    info: string;
    size: number;
  }
  const [value, setValue] = useState(3);
  const [optionVal, setOptionVal] = useState(['1']);
  const [spriteArry, setSpriteArry] = useState<Array<sprite> | null>(null);
  const [curSprite, setCurSprite] = useState<sprite | null>(null);
  const [goods, setGoods] = useState<Array<GoodItem> | null>(null);
  const [boss, setBoss] = useState<sprite | null>(null);
  const [countdown, setCountdowns] = useState<number>(9);
  const [curRound, setcurRound] = useState<string>('user'); //目前只会是user或者boss
  const [timers, setTimers] = useState<Array<NodeJS.Timeout>>([]);
  useEffect(() => {
    Toast({ message: '你的回合' });
    getDetail();
    countdownFn();
  }, []);
  /**
   * 开始计时
   */
  const countdownFn = () => {
    let timer = setInterval(() => {
      setCountdowns((countdown) => {
        // console.log('正常执行');
        if (countdown == 9) {
        }
        if (countdown == 0) {
          // console.log('清楚定时炸弹');
          // setcurRound(curRound == 'user' ? 'boss' : 'user');
          setcurRound((curRound) => {
            Toast({ message: `${curRound == 'user' ? '对方' : '你'}的回合` });
            return curRound == 'user' ? 'boss' : 'user';
          });

          countdown = 10;
        }
        return countdown - 1;
      });
    }, 1000);
    return () => {
      console.log('清楚定时炸弹');

      clearInterval(timer);
    };
  };
  /**
   * 页面加载信息
   */
  const getDetail = () => {
    setGoods(props.goods);

    setSpriteArry(props.spriteArry);
    setCurSprite(props.spriteArry[0]);
    radomBoss();
  };
  /**
   * 随机加载一只boss，目前使用精灵
   */
  const radomBoss = () => {
    //随机加载一只boss，目前使用精灵
    setBoss(props.spriteArry[parseInt(Number(Math.random() * 7))]);
  };
  /**
   * nav切换
   * @param val
   */
  const changeOption = (val: string[]) => {
    if (val && val.length > 0) {
      setOptionVal(val);
      if (val[0] == '5') {
        Dialog.confirm({
          title: '撤退',
          message: '确认要撤退么，撤退有几率失败',
        })
          .then(() => {
            setOptionVal(['1']);
            history.push('/');
          })
          .catch(() => {
            setOptionVal(['1']);
          });
      }
    } else if (optionVal && optionVal.length > 0 && val.length == 0) {
      setOptionVal(optionVal);
    } else {
      setOptionVal(['1']);
    }
  };

  /**
   * 切换精灵
   * @param index
   */
  const changeSprite = (index: number) => {
    Dialog.confirm({
      title: '是否要切换精灵',
      message: '如果切换精灵会耗费一回合，本次回合精灵不能发起攻击',
    })
      .then(() => {
        setCurSprite(spriteArry && spriteArry[index]);
        setOptionVal(['1']);
      })
      .catch(() => {
        setOptionVal(['1']);
      });
  };

  /**
   * 状态点击按钮
   * @param item
   * @returns
   *
   */
  const statsuReturnFn = (item: GoodItem) => {
    if (item.size <= 0) return Toast({ message: `${item.name}数量不足` });
    if (
      item.attr.hp &&
      curSprite &&
      curSprite.attr.maxAttr.hp == curSprite.attr.currAttr.hp
    )
      return Toast({ message: '精灵状态已为最佳' });
    const newgoods =
      goods &&
      goods.map((ite) => {
        if (ite.name == item.name) {
          return {
            ...ite,
            size: ite.size - 1,
          };
        }
        return ite;
      });
    setGoods([...newgoods]);
    props.dispatch({
      type: 'index/saveGoods',
      payload: goods,
    });

    let curHp =
      item.attr.hp &&
      item.attr.hp > curSprite.attr.maxAttr.hp - curSprite.attr.currAttr.hp
        ? curSprite.attr.maxAttr.hp
        : curSprite.attr.currAttr.hp + item.attr.hp;
    let newcursprite = JSON.parse(JSON.stringify(curSprite));
    newcursprite.attr.currAttr.hp = curHp;
    setCurSprite(newcursprite);
    const newspriteArry =
      spriteArry &&
      spriteArry.map((it) => {
        if (curSprite && it.name == curSprite.name) {
          return {
            ...it,
            ...curSprite,
          };
        }
        return it;
      });
    setSpriteArry(newspriteArry);
    props.dispatch({ type: 'index/saveSpriteArry', payload: newspriteArry });
  };
  return (
    <Card round>
      <Card.Header>{/* 战斗场景 */}</Card.Header>
      {curSprite && curSprite.attr && (
        <Card.Body>
          <Flex justify="between" align="center" className={styles.flex}>
            <Flex direction="column" justify="around" className={styles.flex}>
              <Progress
                round
                contentColor={'red'}
                parNum={curSprite.attr.maxAttr.hp}
                contentNum={curSprite.attr.currAttr.hp}
              ></Progress>
              {/* <Progress percentage="50" /> */}
              <Rate
                icon={<Fire />}
                voidIcon={<FireO />}
                value={value}
                onChange={setValue}
              />
              <span> {curSprite && curSprite.name}</span>
            </Flex>
            <Flex direction="column" justify="around" className={styles.flex}>
              <Progress
                round
                contentColor={'blue'}
                parNum={boss.attr.maxAttr.hp}
                contentNum={boss.attr.currAttr.hp}
                mirror
              ></Progress>
              {/* <Progress percentage="50" /> */}
              <Rate
                icon={<Fire />}
                voidIcon={<FireO />}
                value={value}
                onChange={setValue}
              />
              <span style={{ textAlign: 'right' }}> {boss && boss.name}</span>
            </Flex>
          </Flex>
          <Flex
            justify="between"
            align="center"
            className={styles.flex + ' ' + styles.content}
          >
            {/* <Image width="100" src='http://rew00265f.hb-bkt.clouddn.com/img/202207242201386.png' height="100" /> */}
            <Image width="100" height="100" />
            <div className="countdown">{countdown}</div>
            <div className={styles.bossContent}>
              {/* <Image width="100" src='http://rew00265f.hb-bkt.clouddn.com/img/202207242201386.png' height="100" /> */}

              <Image width="100" height="100" />
            </div>
          </Flex>
          <Selector
            style={{
              '--rv-selector-border-radius': '100px',
              '--rv-selector-checked-border':
                'solid var(--adm-color-primary) 1px',
              '--rv-selector-padding': '8px 24px',
            }}
            showCheckMark={false}
            onChange={changeOption}
            value={optionVal}
            options={[
              {
                label: '战斗',
                value: '1',
                disabled: curRound !== 'user',
              },
              {
                label: '道具',
                value: '2',
                disabled: curRound !== 'user',
              },
              {
                label: '捕捉',
                value: '3',
                disabled: curRound !== 'user',
              },
              {
                label: '精灵',
                value: '4',
                disabled: curRound !== 'user',
              },
              {
                label: '撤退',
                value: '5',
                disabled: curRound !== 'user',
              },
            ]}
          />
          <div className={styles.skillBox}>
            {optionVal[0] == '1' && (
              <Flex
                gutter={2}
                justify="around"
                align="center"
                className={styles.flex}
              >
                {!!curSprite &&
                  curSprite.skill &&
                  curSprite.skill.map((item, index) => (
                    <Flex.Item
                      span={5.5}
                      key={index}
                      className={styles.skillItem}
                      style={curRound !== 'user' && { opacity: '0.3' }}
                    >
                      <div className={styles.itemHead}>
                        <div>
                          <span style={{ fontSize: '1.5em' }}>{item.name}</span>
                        </div>
                      </div>
                      <Tag type={item.type == 'atk' ? 'danger' : 'primary'}>
                        {item.type == 'atk' ? '普攻' : '属性'}
                      </Tag>

                      <div>
                        次数：{item.power}/{item.size}
                      </div>

                      <div>威力：{item.power}</div>
                    </Flex.Item>
                  ))}
              </Flex>
            )}
            {optionVal[0] == '2' && (
              <>
                <Grid columnNum={5}>
                  {goods &&
                    goods
                      .filter((it) => it.type == 'statusReurn')
                      .map((i, index) => (
                        <Grid.Item
                          key={index}
                          icon={<ShopO />}
                          text={i.name + ' ' + i.size}
                          onClick={() => statsuReturnFn(i)}
                        />
                      ))}
                </Grid>
              </>
            )}
            {optionVal[0] == '3' && (
              <>
                <Grid columnNum={5}>
                  {goods &&
                    goods
                      .filter((it) => it.type == 'catchSprite')
                      .map((i, index) => (
                        <Grid.Item
                          key={index}
                          icon={<ShopO />}
                          text={i.name + ' ' + i.size}
                        ></Grid.Item>
                      ))}
                </Grid>
              </>
            )}
            {optionVal[0] == '4' && (
              <>
                <Grid columnNum={5}>
                  {!!spriteArry &&
                    spriteArry.length > 0 &&
                    spriteArry.map((i, index) => (
                      <Grid.Item
                        onClick={() => changeSprite(index)}
                        key={index}
                        icon={<ShopO />}
                        text={i.name}
                      />
                    ))}
                </Grid>
              </>
            )}
          </div>
        </Card.Body>
      )}
    </Card>
  );
});
